<?php 
define('ABSPATH', dirname(dirname(__FILE__)).'/');
define('RES', 'resources'.'/');

$ini_path_extra = ABSPATH."lib";
$ini_path = ini_get('include_path');
$ini_path = $ini_path_extra.PATH_SEPARATOR.$ini_path;
ini_set('include_path', $ini_path);

require_once (ABSPATH.'services.php');
require_once ('Utils.php');
require_once ('YSI.php');

$ysi = new YSI(ABSPATH.RES."ysi/", ABSPATH.RES."ysi/ysi.template");
$ysi->load();

define('YSI_BASE', dirname($_SERVER['PHP_SELF']).'/../resources/ysi/styles/');

if (isset($_GET['step'])) $step = $_GET['step'];
else $step = 1;

switch ($step) {
    case 1:
        $title = "QuickMerger &rsaquo; Welcome to QuickMerger Installaton";
        include (dirname(__FILE__).'/views/_welcome_.php');
		break;
	case 2:
		$title = "QuickMerger &rsaquo; Checking the environment";
		
		$state['config-sample'] = '配置文件原型';
		$state['writable'] = '根目录写入权限';
		$state['writable_res'] = 'Resources目录写入权限';
		$state['writable_run'] = 'Runtime目录写入权限';
		$state['mysql'] = 'Mysql扩展模块';
		$state['gd'] = 'GB库扩展模块';
		$state['mbstring'] = 'mbstring扩展模块';
		
		if (!file_exists(dirname(__FILE__).'/config-sample.php'))
		$error['config-sample'] = '找不到config-sample.php，请重新复制文件。';
		
		if (!is_writable(ABSPATH)) 
		$error['writable'] = '根目录写入权限不足，请检查系统目录的权限。';
		
		if (!is_writable(ABSPATH.'resources')) 
		$error['writable_res'] = 'Resources目录写入权限不足，请检查系统目录的权限。';
		
		if (!is_writable(ABSPATH.'runtime')) 
		$error['writable_run'] = 'Runtime目录写入权限不足，请检查系统目录的权限。';
		
		if (!function_exists('mysql_connect'))
		$error['mysql'] = '没有安装mysql扩展模块，请与服务器提供商联系。';
		
		if (!function_exists('gd_info'))
		$error['gd'] = '没有安装GD库扩展模块，请与服务器提供商联系。';
		
		if (!function_exists('mb_substr'))
		$error['mbstring'] = '没有安装mbstring扩展模块，请与服务器提供商联系。';
		
		include (dirname(__FILE__).'/views/_check_.php');
		break;
	case 3:
		$title = "QuickMerger &rsaquo; Collecting informations";
		
		$domain = $_SERVER['SERVER_NAME'];
		$base = substr($_SERVER['PHP_SELF'], 0, strrpos($_SERVER['PHP_SELF'], 'install/index.php'));
		$path = dirname(dirname(__FILE__));
		$db_type = 'mysqli';
		$db_host = 'localhost';
		$db_port = '3306';
		$db_name = '';
		$db_user = '';
		$db_password = '';
		
		include (dirname(__FILE__).'/views/_collect_.php');
		break;
	case 4:
		$domain = trim($_POST['domain']);
		$base = trim($_POST['base']);
		$path = trim($_POST['path']).'/';
		$db_type = trim($_POST['db_type']);
		$db_host = trim($_POST['db_host']);
		$db_port = trim($_POST['db_port']);
		$db_name = trim($_POST['db_name']);
		$db_user = trim($_POST['db_user']);
		$db_password = trim($_POST['db_password']);
		
		PEAR::setErrorHandling(PEAR_ERROR_RETURN);
	    $dsn = array("phptype"  => $db_type,
	                 "hostspec" => $db_host,
	                 "port"     => $db_port,
	                 "database" => $db_name,
	                 "username" => $db_user,
	                 "password" => $db_password);
	    $conn = &DB::connect($dsn);
		if (PEAR::isError($conn)) {
			$error = $conn->getMessage();
			$title = "QuickMerger &rsaquo; Error accured";
			$error_content = "
			<p>连接数据库时发生错误，错误信息为：$error</p>
			<p>请按照以下提示检查您的设置：</p>
			<ul>
				<li>确认您输入的用户名和密码是正确的。</li>
				<li>数据库服务器的域名与端口是正确的。</li>
				<li>数据库服务器已经运行。</li>
				<li>在该数据库服务器中已经建立名为 $db_name 的数据库</li>
			</ul>
			<p>如果您已经确认以上设置都是正确的，或者您无法确定如何正确设置，请联系我们。</p>
			";
			include (dirname(__FILE__).'/views/_error_.php');
			exit;
		}
		
		$configFile = file(dirname(__FILE__).'/config-sample.php');
		
		
		$handle = fopen(ABSPATH . 'config.php', 'w');
		foreach ($configFile as $line_num => $line) {
			switch (substr($line,0,13)) {
				case "define('DOMAI":
					fwrite($handle, str_replace("~DOMAIN~", $domain, $line));
					break;
				case "define('BASE'":
					fwrite($handle, str_replace("~BASE~", $base, $line));
					break;
				case "define('PATH'":
					fwrite($handle, str_replace("~PATH~", $path, $line));
					break;
				case "define('DB_TY":
					fwrite($handle, str_replace("~DB_TYPE~", $db_type, $line));
					break;
				case "define('DB_HO":
					fwrite($handle, str_replace("~DB_HOST~", $db_host, $line));
					break;
				case "define('DB_PO":
					fwrite($handle, str_replace("~DB_PORT~", $db_port, $line));
					break;
				case "define('DB_NA":
					fwrite($handle, str_replace("~DB_NAME~", $db_name, $line));
					break;
				case "define('DB_US":
					fwrite($handle, str_replace("~DB_USER~", $db_user, $line));
					break;
				case "define('DB_PA":
					fwrite($handle, str_replace("~DB_PASSWORD~", $db_password, $line));
					break;
				default:
					fwrite($handle, $line);
			}
		}
		fclose($handle);
		chmod(ABSPATH . 'config.php', 0666);
		$title = "QuickMerger &rsaquo; Database Connected";
		include (dirname(__FILE__).'/views/_connected_.php');
		break;
	case 5:
		require_once(ABSPATH.'config.php');
        require_once(ABSPATH.'constant.php');
        require_once("platform/Interceptor.php");
		require_once("platform/FeatureManager.php");
		
		$featureManager = new FeatureManager(FEATURE_PATH, RUNTIME_PATH.DIRECTORY_SEPARATOR.RUNTIME_PLATFORM_FOLDER,
		     Array('com_yizin_platform_PlatformFeature', 'com_yizin_fm_FMFeature'));
		$featureManager->load();
		
		$features = $featureManager->getFeatures();
		
		$title = "QuickMerger &rsaquo; Plugin Install";
		include (dirname(__FILE__).'/views/_extension_.php');
		break;
	case 6:
		require_once(ABSPATH.'config.php');
        require_once(ABSPATH.'constant.php');
        require_once("platform/Interceptor.php");
		require_once ("platform/FeatureManager.php");
		
		$featureManager = new FeatureManager(FEATURE_PATH, RUNTIME_PATH.DIRECTORY_SEPARATOR.RUNTIME_PLATFORM_FOLDER,
		     Array('com_yizin_platform_PlatformFeature', 'com_yizin_fm_FMFeature'));
		$featureManager->load();
		
		$featureIds = $_POST['id'];
		foreach($featureIds as $featureId) {
			$featureManager->updateFeatureStatus($featureId, 'ENABLED');
		}
		
		$title = "QuickMerger &rsaquo; Adminstrator account";
		include (dirname(__FILE__).'/views/_account_.php');
		break;
	case 7:
		$id = trim($_POST['id']);
        $email = trim($_POST['email']);
        $password = trim($_POST['password']);
        $password1 = trim($_POST['password1']);
		
		$error = array();
        if ($id == "") {
            $error['id'] = "用户名不能为空";
        } elseif (!Utils::isIdentifier($id)) {
            $error['id'] = "用户名必须由字母或数字组成，数字开头";
        } elseif (strlen($id) < 4 || strlen($id) > 20) {
            $error['id'] = "用户名长度必须在4-20之间";
        } elseif ($email == "") {
            $error['email'] = "邮箱不能为空";
        } elseif (!Utils::isEmail($email)) {
            $error['email'] = "邮箱不符合要求";
        } elseif ($nickname != "" && (strlen($nickname) < 4 || strlen($nickname) > 20)) {
            $error['nickname'] = "昵称长度必须在4-20之间";
        } elseif ($password == "") {
            $error['password'] = "密码不能为空";
        } elseif (strlen($password) < 6 || strlen($password) > 30) {
            $error['password'] = "密码长度必须在6-30之间";
        } elseif ($password1 != $password) {
            $error['password1'] = "必须和上面的密码相同";
        }
		
		if (count($error) != 0) {
            $GLOBALS['error'] = $error;
            $GLOBALS['id'] = $id;
            $GLOBALS['email'] = $email;
            
            include (dirname(__FILE__).'/views/_account_.php');
            exit;
        }
        
        require_once(ABSPATH.'config.php');
        require_once(ABSPATH.'constant.php');
        require_once("platform/Interceptor.php");
        require_once(ABSPATH.'features/com.yizin.site/services.php');
		
        $serial = user_create(array('id'=>$id, 'email'=>$email, 'password'=>$password));
        if ($serial) {
        	$roleId = 'admin';
        	$role = role_getByField('id', $roleId);
			role_grant($serial, $role['serial']);
			
			$access = fopen((dirname(__FILE__).'/.htaccess'), 'w');
			fwrite($access, 'Order deny,allow\n\rDeny from all');
			
			include (dirname(__FILE__).'/views/_login_.php');
        }
}

?>
